package com.example.demojava.controller;

import com.example.demojava.entity.FileInfo;
import com.example.demojava.service.FileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

/**
 * 文件上传接口
 */
@RestController
@RequestMapping("/files")
public class FileController {

    @Autowired
    private FileService fileService;

    /**
     * 初始化文件上传
     * 在开始上传文件分片之前，需要先调用此接口初始化上传
     * 
     * 请求示例：
     * POST /api/files/init?fileName=test.pdf&fileHash=abc123&totalSize=1048576
     */
    @PostMapping("/init")
    public ResponseEntity<FileInfo> initUpload(
            @RequestParam String fileName,
            @RequestParam String fileHash,
            @RequestParam Long totalSize) {
        return ResponseEntity.ok(fileService.initUpload(fileName, fileHash, totalSize));
    }

    /**
     * 上传文件分片
     * 将文件分片上传到服务器
     * 
     * 请求示例：
     * POST /api/files/chunk
     * Content-Type: multipart/form-data
     * 
     * Form Data:
     * - chunk: [文件分片数据]
     * - fileHash: abc123
     * - chunkNumber: 1
     */
    @PostMapping("/chunk")
    public ResponseEntity<FileInfo> uploadChunk(
            @RequestParam String fileHash,
            @RequestParam Long chunkNumber,
            @RequestParam MultipartFile chunk) {
        return ResponseEntity.ok(fileService.uploadChunk(fileHash, chunkNumber, chunk));
    }

    /**
     * 获取文件上传进度
     * 查询文件的上传状态和进度
     * 
     * 请求示例：
     * GET /api/files/progress/abc123
     */
    @GetMapping("/progress/{fileHash}")
    public ResponseEntity<FileInfo> getUploadProgress(@PathVariable String fileHash) {
        return ResponseEntity.ok(fileService.getUploadProgress(fileHash));
    }

    /**
     * 完成文件上传
     * 所有分片上传完成后，调用此接口合并文件
     * 
     * 请求示例：
     * POST /api/files/complete/abc123
     */
    @PostMapping("/complete/{fileHash}")
    public ResponseEntity<Void> completeUpload(@PathVariable String fileHash) {
        fileService.completeUpload(fileHash);
        return ResponseEntity.ok().build();
    }
}